package com.lagou.edu.controller;

import com.lagou.edu.pojo.Resume;
import com.lagou.edu.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/sss")
public class ResumeController {

    @Autowired
    private ResumeService resumeService;

    @GetMapping("/resumes")
    public ModelAndView getResumes() {

        ModelAndView modelAndView = new ModelAndView();

        List<Resume> resumes = resumeService.getResumes();
        modelAndView.addObject("resumes", resumes);
        modelAndView.addObject("isOnloaded", true);
        modelAndView.setViewName("list");

        return modelAndView;
    }

    @PostMapping("/resumes")
    public ModelAndView add(String actionType, String address, String name, String phone) {

        ModelAndView modelAndView = new ModelAndView();

        if ("do".equals(actionType)) {
            resumeService.addResume(address, name, phone);
            modelAndView.setViewName("list");
            return modelAndView;

        } else {
            Resume resume = new Resume();
            modelAndView.addObject("resume", resume);
            modelAndView.addObject("editType", "add");
            modelAndView.setViewName("edit");
            return modelAndView;
        }
    }

    @PutMapping("/resumes/{id}")
    public ModelAndView update(String actionType, @PathVariable Long id, String address, String name, String phone) {

        ModelAndView modelAndView = new ModelAndView();

        if ("do".equals(actionType)) {
            resumeService.updateResume(id, address, name, phone);
            modelAndView.setViewName("list");
            return modelAndView;

        } else {
            Resume resume = resumeService.getResumeById(id);
            modelAndView.addObject("resume", resume);
            modelAndView.addObject("editType", "update");
            modelAndView.setViewName("edit");
            return modelAndView;
        }
    }

    @DeleteMapping("/resumes/{id}")
    public ModelAndView removeResume(@PathVariable Long id) {

        resumeService.removeResume(id);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("list");

        return modelAndView;
    }
}
